﻿using System;
using System.Collections.Generic;
using System.Data;
using PPI.Entities;
using VMind.Global;

namespace PPI.Client.Logic
{
    public class LUser
    {
        public static bool ValidUser(EUser user)
        {
            DataTable dt = WebConsumer.WUser.GetAll().Tables[0];
            List<EUser> systemUsers = ParseUser(dt);

            Int32 returnUserindex = systemUsers.IndexOf(user);
            if (returnUserindex > -1)
            {
                return systemUsers[returnUserindex].IsAdministrator;
            }else
            {
                return false;
            }
        }

        public static bool ValidUser(List<EUser> systemUsers, EUser user)
        {
            Int32 returnUserindex = systemUsers.IndexOf(user);
            if (returnUserindex > -1)
            {
                return systemUsers[returnUserindex].IsAdministrator;
            }
            else
            {
                return false;
            }
        }

        private static List<EUser> ParseUser(DataTable dt)
        {
            List<EUser> returnUsers = new List<EUser>();

            foreach (DataRow dr in dt.Rows)
            {
                EUser tmpUser = new EUser(ConvertHelper.ToInt32(dr["UserId"]),dr["Username"].ToString(),dr["Password"].ToString(),ConvertHelper.Tobool(dr["Administrator"]));

                returnUsers.Add(tmpUser);
            }

            return returnUsers;
        }

        public static List<EUser> GetAll()
        {
            return ParseUser(WebConsumer.WUser.GetAll().Tables[0]);

        }


        public static Int32 Save(EUser user)
        {
            return WebConsumer.WUser.Save(user.Id, user.Username, user.Password, user.IsAdministrator);
        }
    }
}
